package com.example.controller;

import com.example.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@CrossOrigin
@Api(value = "文件上传",tags = "文件上传")
public class FileController {
    //文件存储路径
    @Value("${mall.path}")
    private String basePath;

    @PostMapping
    @ApiOperation(value = "图片上传")
    public Result upload(@RequestParam("file") MultipartFile userImg){
        //头像上传的文件名
        String filename = userImg.getOriginalFilename();
        //获取文件名后缀
        String type = filename.substring(filename.lastIndexOf("."));
        //使用uuid生成新的文件名拼接
        String newFilename = UUID.randomUUID().toString()+type;
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        try {
            userImg.transferTo(new File(basePath+newFilename));
        }catch (IOException e){
            e.printStackTrace();
        }
        return Result.success(newFilename);
    }

    @GetMapping("/{name}")
    @ApiOperation(value = "图片显示", notes = "提交所需参数 name=>文件名 演示json参数是否接收成功")
    public void download(@PathVariable String name, HttpServletResponse response){
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
